package cn.lvji.springboot.learn3.controller;

import cn.lvji.springboot.learn3.vo.ScenicVO;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @author zhouzx
 */
@Controller
public class ScenicController implements CommandLineRunner {
    private Map<Long,ScenicVO> map;

    @GetMapping("/scenic/list")
    public String list(Model model){
        List<ScenicVO> list = new ArrayList<>(map.size());
        Set<Map.Entry<Long, ScenicVO>> set = map.entrySet();
        Iterator<Map.Entry<Long, ScenicVO>> it = set.iterator();
        while (it.hasNext()) {
            list.add(it.next().getValue());
        }
        model.addAttribute("scenics", list);
        return "/list";
    }

    @ResponseBody
    @GetMapping("/scenic")
    public Map<Long,ScenicVO> all() {
        return map;
    }
    @GetMapping("/scenic/view")
    public ModelAndView view(Model model){
        ModelAndView view = new ModelAndView();
        List<ScenicVO> list = new ArrayList<>(map.size());
        Set<Map.Entry<Long, ScenicVO>> set = map.entrySet();
        Iterator<Map.Entry<Long, ScenicVO>> it = set.iterator();
        while (it.hasNext()) {
            list.add(it.next().getValue());
        }
        view.addObject("scenics", list);
        view.setViewName("/view");
        return view;
    }


    @GetMapping(path = "/{id}/scenic")
    public String getScenic(@PathVariable Long id, Model model) {
        ScenicVO scenicVO = map.get(id);
        model.addAttribute("scenic",scenicVO);
        return "/scenic";
    }

    /**
     * 启动执行方法
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        map = new HashMap<>(10);
        for (int i = 0; i < 10; i++) {
            ScenicVO scenic;
            if (i % 2 == 0) {
                scenic = new ScenicVO(Long.valueOf(i), "name" + i, 1, "美景", "广东广州",null);
            } else {
                scenic = new ScenicVO(Long.valueOf(i), "name" + i, 2, "美景", "广东广州",null);
            }
            map.put(Long.valueOf(i), scenic);
        }
    }
}
